<template>
  <el-card>
    <div class="report-header">
      <h3>库存明细统计表</h3>
      <div class="report-controls">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
          style="width: 250px;"
        />
        <el-button 
          type="primary"
          @click="switchOutboundStatus"
          style="margin-left: 12px;"
        >
          {{ outboundStatus === '未出库' ? '显示已出库' : '显示未出库' }}
        </el-button>
        <el-button type="success" @click="exportExcel">导出Excel</el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="商品名称">
          <el-input
            v-model="filterForm.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 180px;"
            @input="handleFilterChange"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select
            v-model="filterForm.warehouse"
            placeholder="请选择仓库"
            clearable
            style="width: 150px;"
            @change="handleWarehouseChange"
          >
            <el-option label="上海仓" value="上海仓" />
            <el-option label="北京仓" value="北京仓" />
            <el-option label="广州仓" value="广州仓" />
            <el-option label="深圳仓" value="深圳仓" />
          </el-select>
        </el-form-item>
        <el-form-item label="库位">
          <el-select
            v-model="filterForm.location"
            placeholder="请选择库位"
            clearable
            style="width: 120px;"
            @change="handleFilterChange"
            :disabled="!filterForm.warehouse"
          >
            <el-option
              v-for="location in availableLocations"
              :key="location"
              :label="location"
              :value="location"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFilterChange">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="pagedData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="productId" label="商品ID" width="120" />
      <el-table-column prop="trackingNumber" label="物流单号" width="150" />
      <el-table-column prop="productName" label="商品名称" width="200" />
      <el-table-column prop="category" label="商品分类" width="120" />
      <el-table-column prop="warehouse" label="仓库" width="100" />
      <el-table-column prop="location" label="库位" width="100" />
      <el-table-column prop="currentStock" label="当前库存" width="100">
        <template #default="scope">
          <span class="stock-value">{{ scope.row.currentStock }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="outboundStatus" label="出库状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.outboundStatus === '已出库' ? 'success' : 'warning'" size="small">
            {{ scope.row.outboundStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="inboundTime" label="入库时间" width="180" />
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="mt-2"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="filteredTableData.length"
      :page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      v-model:current-page="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

const dateRange = ref(['2024-08-01', '2024-08-14'])
const tableData = ref<any[]>([])
const outboundStatus = ref('未出库') // 默认显示未出库
const page = ref(1)
const pageSize = ref(20)

// 筛选表单
const filterForm = ref({
  productName: '',
  warehouse: '',
  location: ''
})

// 商品分类
const categories = ['电子产品', '服装鞋帽', '家居用品', '食品饮料', '图书音像', '运动户外']

// 仓库与库位的映射关系
const warehouseLocationMap = {
  '上海仓': ['A1-01', 'A1-02', 'A1-03', 'A1-04', 'A1-05', 'B1-01', 'B1-02', 'B1-03', 'B1-04', 'B1-05'],
  '北京仓': ['C1-01', 'C1-02', 'C1-03', 'C1-04', 'C1-05', 'D1-01', 'D1-02', 'D1-03', 'D1-04', 'D1-05'],
  '广州仓': ['E1-01', 'E1-02', 'E1-03', 'E1-04', 'E1-05', 'F1-01', 'F1-02', 'F1-03', 'F1-04', 'F1-05'],
  '深圳仓': ['G1-01', 'G1-02', 'G1-03', 'G1-04', 'G1-05', 'H1-01', 'H1-02', 'H1-03', 'H1-04', 'H1-05']
}

// 根据选择的仓库获取可用的库位
const availableLocations = computed(() => {
  if (!filterForm.value.warehouse) {
    return []
  }
  return warehouseLocationMap[filterForm.value.warehouse as keyof typeof warehouseLocationMap] || []
})

// 筛选后的数据
const filteredTableData = computed(() => {
  let filtered = tableData.value

  // 按出库状态筛选
  filtered = filtered.filter(item => item.outboundStatus === outboundStatus.value)

  if (filterForm.value.productName) {
    filtered = filtered.filter(item => 
      item.productName.toLowerCase().includes(filterForm.value.productName.toLowerCase())
    )
  }

  if (filterForm.value.warehouse) {
    filtered = filtered.filter(item => item.warehouse === filterForm.value.warehouse)
  }

  if (filterForm.value.location) {
    filtered = filtered.filter(item => item.location === filterForm.value.location)
  }

  return filtered
})

// 分页数据
const pagedData = computed(() => {
  const start = (page.value - 1) * pageSize.value
  return filteredTableData.value.slice(start, start + pageSize.value)
})

const generateStockDetailData = (startDate: string, endDate: string) => {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const data: any[] = []
  
  // 计算日期范围内的天数
  const daysDiff = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))
  
  // 生成库存明细数据
  for (let i = 1; i <= 50; i++) {
    const currentStock = Math.floor(Math.random() * 200) + 10
    
    const warehouse = ['上海仓', '北京仓', '广州仓', '深圳仓'][i % 4]
    const warehouseLocations = warehouseLocationMap[warehouse as keyof typeof warehouseLocationMap]
    const location = warehouseLocations[i % warehouseLocations.length]
    
    // 根据时间范围生成入库时间
    const randomDay = Math.floor(Math.random() * daysDiff)
    const randomDate = new Date(start.getTime() + randomDay * 24 * 60 * 60 * 1000)
    const year = randomDate.getFullYear()
    const month = String(randomDate.getMonth() + 1).padStart(2, '0')
    const day = String(randomDate.getDate()).padStart(2, '0')
    const hour = String(Math.floor(Math.random() * 24)).padStart(2, '0')
    const minute = String(Math.floor(Math.random() * 60)).padStart(2, '0')
    const second = String(Math.floor(Math.random() * 60)).padStart(2, '0')
    
    data.push({
      productId: `SKU${String(i).padStart(4, '0')}`,
      trackingNumber: `SF${String(Date.now()).slice(-8)}${String(i).padStart(4, '0')}`,
      productName: `商品${i}号`,
      category: categories[i % categories.length],
      warehouse,
      location,
      currentStock,
      outboundStatus: ['已出库', '未出库'][i % 2], // 随机分配出库状态
      inboundTime: `${year}-${month}-${day} ${hour}:${minute}:${second}`
    })
  }
  
  return data
}

const handleDateChange = () => {
  updateData()
}

const handleFilterChange = () => {
  // 筛选逻辑已在 computed 中处理
  page.value = 1 // 筛选时重置到第一页
}

const handleWarehouseChange = () => {
  // 当仓库改变时，清空库位选择
  filterForm.value.location = ''
  // 筛选逻辑已在 computed 中处理
}

const switchOutboundStatus = () => {
  outboundStatus.value = outboundStatus.value === '未出库' ? '已出库' : '未出库'
  page.value = 1 // 切换状态时重置到第一页
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  page.value = 1
}

const handleCurrentChange = (val: number) => {
  page.value = val
}

const resetFilter = () => {
  filterForm.value.productName = ''
  filterForm.value.warehouse = ''
  filterForm.value.location = ''
  page.value = 1 // 重置筛选时也重置到第一页
}

const updateData = () => {
  const data = generateStockDetailData(dateRange.value[0], dateRange.value[1])
  tableData.value = data
}



const exportExcel = () => {
  if (filteredTableData.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }

  const exportData = filteredTableData.value.map(item => ({
    '商品ID': item.productId,
    '物流单号': item.trackingNumber,
    '商品名称': item.productName,
    '商品分类': item.category,
    '仓库': item.warehouse,
    '库位': item.location,
    '当前库存': item.currentStock,
    '出库状态': item.outboundStatus,
    '入库时间': item.inboundTime
  }))

  // 计算汇总数据
  const totals = {
    '商品ID': '汇总',
    '物流单号': '-',
    '商品名称': '全部商品',
    '商品分类': '-',
    '仓库': '-',
    '库位': '-',
    '当前库存': exportData.reduce((sum, item) => sum + item['当前库存'], 0),
    '出库状态': outboundStatus.value,
    '入库时间': '-'
  }

  // 将汇总行添加到数据顶部
  exportData.unshift(totals)

  const ws = XLSX.utils.json_to_sheet(exportData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '库存明细统计')
  
  XLSX.writeFile(wb, `库存明细统计报表_${dateRange.value[0]}_${dateRange.value[1]}.xlsx`)
  ElMessage.success('导出成功')
}

onMounted(() => {
  updateData()
})
</script>

<style scoped>
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.report-header h3 {
  margin: 0;
  color: #303133;
}

.report-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-section {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-section .el-form {
  margin: 0;
}

.filter-section .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.stock-value {
  color: #409eff;
  font-weight: bold;
}

.mt-2 {
  margin-top: 16px;
}
</style> 